<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Login extends CI_Controller {

    function __construct() {
        parent::__construct();
    }

    function index() {

        if ($this->session->userdata('login') == TRUE) {
            redirect('main');
        } else {
            $data = array();
            $data['title'] = "Karaoke App";
            
            $this->load->view('login-view', $data);
        }
    }

    function proses() {

        $this->load->model("login_model");

        $username = $this->input->post('username');
        //$password = md5($this->input->post('password'));
        $password = $this->input->post('password');

        
        if (!empty($username) || !empty($password)) {

            if ($this->login_model->check_user($username, $this->_encode_password($password))) {
                
                $query = $this->db->query("SELECT m_user.username,  m_user.email,  m_role.id as id_role, m_role.role FROM m_user left join m_role on(m_user.id_role = m_role.id ) WHERE username = '$username' LIMIT 0, 1");            
                     
                
                $rs = $query->row_array();
                
                $data = array(
                    'username' => $username, 
                    'email' => $rs['email'],
                    'id_role' => $rs['id_role'],
                    'login' => TRUE
                    );
                
                $this->session->set_userdata($data);
                redirect('main');
            } else {

                //echo "<script>alert('Maaf username dan password anda salah');</script>";
                redirect('login');
                //echo '<meta http-equiv="refresh" content="10" url="' . base_url() . 'login">';
            }
        } else {
            redirect('login');
        }
    }
    
    
    private function _encode_password($string)
    {
        $string .= $this->config->item('encryption_key');
	// Return the SHA-1 encryption
        return sha1($string);
    }

    function proses_logout() {
        $this->session->sess_destroy();
        redirect("login");
    }


}
